import { useState, useEffect } from "react";
import "./Routing.css";

// 模拟路由系统
function Router({ routes }) {
  const [currentPath, setCurrentPath] = useState(window.location.pathname);
  
  useEffect(() => {
    const handlePopState = () => {
      setCurrentPath(window.location.pathname);
    };
    
    window.addEventListener('popstate', handlePopState);
    
    return () => {
      window.removeEventListener('popstate', handlePopState);
    };
  }, []);
  
  const navigate = (path) => {
    window.history.pushState({}, '', path);
    setCurrentPath(path);
  };
  
  // 查找匹配的路由
  const matchedRoute = routes.find(route => {
    if (route.path === currentPath) return true;
    
    // 处理动态路由参数
    const routeSegments = route.path.split('/');
    const pathSegments = currentPath.split('/');
    
    if (routeSegments.length !== pathSegments.length) return false;
    
    return routeSegments.every((segment, index) => {
      return segment.startsWith(':') || segment === pathSegments[index];
    });
  });
  
  // 提取路由参数
  const params = {};
  if (matchedRoute && matchedRoute.path.includes(':')) {
    const routeSegments = matchedRoute.path.split('/');
    const pathSegments = currentPath.split('/');
    
    routeSegments.forEach((segment, index) => {
      if (segment.startsWith(':')) {
        const paramName = segment.substring(1);
        params[paramName] = pathSegments[index];
      }
    });
  }
  
  const RouteComponent = matchedRoute ? matchedRoute.component : NotFound;
  
  return (
    <div className="router">
      <Navigation currentPath={currentPath} navigate={navigate} />
      <main className="route-content">
        <RouteComponent params={params} navigate={navigate} />
      </main>
    </div>
  );
}

// 导航组件
function Navigation({ currentPath, navigate }) {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  
  const toggleMenu = () => {
    setIsMenuOpen(!isMenuOpen);
  };
  
  const navItems = [
    { path: '/', label: '首页' },
    { path: '/about', label: '关于' },
    { path: '/users', label: '用户列表' },
    { path: '/contact', label: '联系我们' },
  ];
  
  return (
    <nav className="navigation">
      <div className="nav-brand">
        <h2>React 路由示例</h2>
        <button className="menu-toggle" onClick={toggleMenu}>
          {isMenuOpen ? '✕' : '☰'}
        </button>
      </div>
      
      <ul className={`nav-menu ${isMenuOpen ? 'open' : ''}`}>
        {navItems.map(item => (
          <li key={item.path} className="nav-item">
            <a
              href={item.path}
              className={`nav-link ${currentPath === item.path ? 'active' : ''}`}
              onClick={(e) => {
                e.preventDefault();
                navigate(item.path);
                setIsMenuOpen(false);
              }}
            >
              {item.label}
            </a>
          </li>
        ))}
      </ul>
    </nav>
  );
}

// 首页组件
function Home({ navigate }) {
  const [featuredPosts, setFeaturedPosts] = useState([
    { id: 1, title: 'React 18 新特性', excerpt: '了解 React 18 带来的激动人心的新功能...' },
    { id: 2, title: 'Hooks 最佳实践', excerpt: '学习如何在实际项目中有效使用 Hooks...' },
    { id: 3, title: '性能优化技巧', excerpt: '掌握 React 应用的性能优化方法...' },
  ]);
  
  return (
    <div className="home-page">
      <div className="hero-section">
        <h1>欢迎来到 React 学习中心</h1>
        <p>探索现代前端开发的强大工具</p>
        <div className="hero-actions">
          <button className="btn-primary" onClick={() => navigate('/about')}>
            了解更多
          </button>
          <button className="btn-secondary" onClick={() => navigate('/users')}>
            查看用户
          </button>
        </div>
      </div>
      
      <div className="featured-posts">
        <h2>精选文章</h2>
        <div className="posts-grid">
          {featuredPosts.map(post => (
            <div key={post.id} className="post-card">
              <h3>{post.title}</h3>
              <p>{post.excerpt}</p>
              <button 
                className="btn-link"
                onClick={() => navigate(`/posts/${post.id}`)}
              >
                阅读更多 →
              </button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// 关于页面组件
function About({ navigate }) {
  const [teamMembers] = useState([
    { name: '张三', role: '前端工程师', avatar: '👨‍💻' },
    { name: '李四', role: 'UI 设计师', avatar: '👩‍🎨' },
    { name: '王五', role: '产品经理', avatar: '👨‍💼' },
  ]);
  
  return (
    <div className="about-page">
      <div className="about-header">
        <h1>关于我们</h1>
        <p>我们是一支充满激情的开发团队，致力于创建优秀的 Web 应用</p>
      </div>
      
      <div className="about-content">
        <section className="mission-section">
          <h2>我们的使命</h2>
          <p>通过现代前端技术，为用户提供卓越的数字体验。我们相信好的技术应该简单易用，同时功能强大。</p>
        </section>
        
        <section className="team-section">
          <h2>团队成员</h2>
          <div className="team-grid">
            {teamMembers.map((member, index) => (
              <div key={index} className="team-member">
                <div className="member-avatar">{member.avatar}</div>
                <h3>{member.name}</h3>
                <p>{member.role}</p>
              </div>
            ))}
          </div>
        </section>
        
        <section className="tech-section">
          <h2>技术栈</h2>
          <div className="tech-grid">
            {['React', 'JavaScript', 'CSS', 'HTML5', 'Git', 'Webpack'].map(tech => (
              <div key={tech} className="tech-item">{tech}</div>
            ))}
          </div>
        </section>
      </div>
    </div>
  );
}

// 用户列表组件
function UsersList({ navigate }) {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  
  useEffect(() => {
    // 模拟 API 调用
    setTimeout(() => {
      setUsers([
        { id: 1, name: '张三', email: 'zhangsan@example.com', role: '管理员' },
        { id: 2, name: '李四', email: 'lisi@example.com', role: '编辑' },
        { id: 3, name: '王五', email: 'wangwu@example.com', role: '用户' },
        { id: 4, name: '赵六', email: 'zhaoliu@example.com', role: '编辑' },
        { id: 5, name: '钱七', email: 'qianqi@example.com', role: '用户' },
      ]);
      setLoading(false);
    }, 1000);
  }, []);
  
  const filteredUsers = users.filter(user =>
    user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    user.email.toLowerCase().includes(searchTerm.toLowerCase())
  );
  
  if (loading) {
    return (
      <div className="loading">
        <div className="spinner"></div>
        <p>加载用户数据中...</p>
      </div>
    );
  }
  
  return (
    <div className="users-page">
      <div className="users-header">
        <h1>用户列表</h1>
        <div className="search-box">
          <input
            type="text"
            placeholder="搜索用户..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
      </div>
      
      <div className="users-grid">
        {filteredUsers.map(user => (
          <div key={user.id} className="user-card">
            <div className="user-avatar">
              {user.name.charAt(0)}
            </div>
            <div className="user-info">
              <h3>{user.name}</h3>
              <p>{user.email}</p>
              <span className="user-role">{user.role}</span>
            </div>
            <button 
              className="btn-view"
              onClick={() => navigate(`/users/${user.id}`)}
            >
              查看详情
            </button>
          </div>
        ))}
      </div>
      
      {filteredUsers.length === 0 && (
        <div className="no-results">
          <p>没有找到匹配的用户</p>
        </div>
      )}
    </div>
  );
}

// 用户详情组件
function UserDetail({ params, navigate }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('profile');
  
  useEffect(() => {
    // 模拟 API 调用
    setTimeout(() => {
      setUser({
        id: parseInt(params.id),
        name: '张三',
        email: 'zhangsan@example.com',
        role: '管理员',
        joinDate: '2022-01-15',
        lastLogin: '2023-11-20',
        posts: 42,
        comments: 128,
        likes: 256,
      });
      setLoading(false);
    }, 800);
  }, [params.id]);
  
  if (loading) {
    return (
      <div className="loading">
        <div className="spinner"></div>
        <p>加载用户详情中...</p>
      </div>
    );
  }
  
  if (!user) {
    return (
      <div className="not-found">
        <h2>用户未找到</h2>
        <p>请求的用户不存在</p>
        <button onClick={() => navigate('/users')}>返回用户列表</button>
      </div>
    );
  }
  
  return (
    <div className="user-detail-page">
      <div className="user-detail-header">
        <button className="back-btn" onClick={() => navigate('/users')}>
          ← 返回
        </button>
        <h1>用户详情</h1>
      </div>
      
      <div className="user-detail-content">
        <div className="user-profile-card">
          <div className="user-avatar-large">
            {user.name.charAt(0)}
          </div>
          <div className="user-basic-info">
            <h2>{user.name}</h2>
            <p>{user.email}</p>
            <span className="user-role-badge">{user.role}</span>
          </div>
        </div>
        
        <div className="user-tabs">
          <div className="tab-nav">
            {['profile', 'activity', 'settings'].map(tab => (
              <button
                key={tab}
                className={`tab-btn ${activeTab === tab ? 'active' : ''}`}
                onClick={() => setActiveTab(tab)}
              >
                {tab === 'profile' ? '个人资料' : tab === 'activity' ? '活动记录' : '设置'}
              </button>
            ))}
          </div>
          
          <div className="tab-content">
            {activeTab === 'profile' && (
              <div className="profile-tab">
                <div className="info-grid">
                  <div className="info-item">
                    <label>用户 ID</label>
                    <span>{user.id}</span>
                  </div>
                  <div className="info-item">
                    <label>加入日期</label>
                    <span>{user.joinDate}</span>
                  </div>
                  <div className="info-item">
                    <label>最后登录</label>
                    <span>{user.lastLogin}</span>
                  </div>
                  <div className="info-item">
                    <label>角色</label>
                    <span>{user.role}</span>
                  </div>
                </div>
              </div>
            )}
            
            {activeTab === 'activity' && (
              <div className="activity-tab">
                <div className="stats-grid">
                  <div className="stat-card">
                    <h3>{user.posts}</h3>
                    <p>发布文章</p>
                  </div>
                  <div className="stat-card">
                    <h3>{user.comments}</h3>
                    <p>评论</p>
                  </div>
                  <div className="stat-card">
                    <h3>{user.likes}</h3>
                    <p>获赞</p>
                  </div>
                </div>
              </div>
            )}
            
            {activeTab === 'settings' && (
              <div className="settings-tab">
                <div className="settings-form">
                  <div className="form-group">
                    <label>用户名</label>
                    <input type="text" defaultValue={user.name} />
                  </div>
                  <div className="form-group">
                    <label>邮箱</label>
                    <input type="email" defaultValue={user.email} />
                  </div>
                  <div className="form-group">
                    <label>角色</label>
                    <select defaultValue={user.role}>
                      <option value="用户">用户</option>
                      <option value="编辑">编辑</option>
                      <option value="管理员">管理员</option>
                    </select>
                  </div>
                  <button className="btn-save">保存更改</button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// 联系我们组件
function Contact() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    subject: '',
    message: ''
  });
  const [submitted, setSubmitted] = useState(false);
  
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  const handleSubmit = (e) => {
    e.preventDefault();
    // 模拟表单提交
    console.log('表单数据:', formData);
    setSubmitted(true);
    setTimeout(() => {
      setSubmitted(false);
      setFormData({
        name: '',
        email: '',
        subject: '',
        message: ''
      });
    }, 3000);
  };
  
  return (
    <div className="contact-page">
      <div className="contact-header">
        <h1>联系我们</h1>
        <p>有任何问题或建议？我们很乐意听到您的声音</p>
      </div>
      
      <div className="contact-content">
        <div className="contact-info">
          <div className="contact-item">
            <h3>📧 邮箱</h3>
            <p>contact@example.com</p>
          </div>
          <div className="contact-item">
            <h3>📞 电话</h3>
            <p>+86 123 4567 8900</p>
          </div>
          <div className="contact-item">
            <h3>📍 地址</h3>
            <p>北京市朝阳区某某街道123号</p>
          </div>
        </div>
        
        <div className="contact-form">
          {submitted ? (
            <div className="success-message">
              <h3>✅ 消息已发送</h3>
              <p>感谢您的联系，我们会尽快回复您！</p>
            </div>
          ) : (
            <form onSubmit={handleSubmit}>
              <div className="form-group">
                <label htmlFor="name">姓名</label>
                <input
                  type="text"
                  id="name"
                  name="name"
                  value={formData.name}
                  onChange={handleChange}
                  required
                />
              </div>
              
              <div className="form-group">
                <label htmlFor="email">邮箱</label>
                <input
                  type="email"
                  id="email"
                  name="email"
                  value={formData.email}
                  onChange={handleChange}
                  required
                />
              </div>
              
              <div className="form-group">
                <label htmlFor="subject">主题</label>
                <input
                  type="text"
                  id="subject"
                  name="subject"
                  value={formData.subject}
                  onChange={handleChange}
                  required
                />
              </div>
              
              <div className="form-group">
                <label htmlFor="message">消息</label>
                <textarea
                  id="message"
                  name="message"
                  rows="5"
                  value={formData.message}
                  onChange={handleChange}
                  required
                ></textarea>
              </div>
              
              <button type="submit" className="btn-submit">发送消息</button>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

// 404 页面组件
function NotFound({ navigate }) {
  return (
    <div className="not-found-page">
      <div className="not-found-content">
        <h1>404</h1>
        <h2>页面未找到</h2>
        <p>抱歉，您访问的页面不存在</p>
        <div className="not-found-actions">
          <button onClick={() => navigate('/')} className="btn-primary">
            返回首页
          </button>
          <button onClick={() => window.history.back()} className="btn-secondary">
            返回上页
          </button>
        </div>
      </div>
    </div>
  );
}

// 路由配置
const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
  { path: '/users', component: UsersList },
  { path: '/users/:id', component: UserDetail },
  { path: '/contact', component: Contact },
];

// 主组件
function Routing() {
  return (
    <div className="routing-example">
      <Router routes={routes} />
    </div>
  );
}

export default Routing;